#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import time
import os
import re
import platform
import argparse

from subprocess import call
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class FileChangeHandler(FileSystemEventHandler):
    def on_modified(self, event):
        src_path = event.src_path.replace('\\','/')
        if src_path in SYNC_FILE_LIST:
            os.chdir(args.config_root)
            git_add_cmd = "git add -A"
            git_commit_cmd = "git commit -m " + re.escape("Update "+os.path.basename(src_path))
            if platform.system() == "Windows":
                git_commit_cmd = "git commit -m Update."
            git_pull_cmd = f"git pull origin {args.branch}"
            git_push_cmd = f"git push origin {args.branch}"

            call(
                git_add_cmd + "&&" +
                git_commit_cmd + "&&" +
                git_pull_cmd + "&&" +
                git_push_cmd,
                shell=True
            )


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--branch', '-b', default='master', 
                        help='远程仓库对应的目标分支')
    parser.add_argument('--config_root', '-r', 
                        default=os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 
                        help='要同步的文件夹所在位置\ngit root path for files to push to remote')
    
    args = parser.parse_args()
    
    # files to synchronize
    SYNC_FILE_LIST = []
    f = open(os.path.join(args.config_root, "file_list.txt"), "r")
    try:
        SYNC_FILE_LIST = [line.strip().replace('\\','/') for line in f if os.path.isfile(line.strip().replace('\\','/'))]
    except Exception as e:
        raise e
    finally:
        f.close()
        
    observer = Observer()
    event_handler = FileChangeHandler()

    for file_path in SYNC_FILE_LIST:
        observer.schedule(event_handler, path=os.path.dirname(os.path.realpath(file_path)), recursive=False)

    observer.start()

    try:
        while True:
            time.sleep(10)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
